package v3;

import org.freedesktop.dbus.DBusPath;
import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
import org.freedesktop.dbus.types.Variant;
import v3.inter.ObjectManagerInterface;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Map;

import static v3.GATTApplication.*;

/**
 * Linux系统 并安装BlueZ 5.43+
 *
 * 蓝牙适配器 支持BLE
 *
 * NetworkManager 用于WiFi管理
 *
 * root权限 用于蓝牙操作
 */
public class BluetoothGATTApp {

    private DBusConnection dbusConnection;
    private WiFiManager wifiManager;
    private GATTApplication gattApp;

    public void start() {
        try {

            // 建立D-Bus连接
            dbusConnection = DBusConnection.getConnection(DBusConnection.DBusBusType.SYSTEM);
            // 验证连接是否活跃
            if (!dbusConnection.isConnected()) {
                System.err.println("D-Bus连接未建立");
            } else {
                System.err.println("D-Bus连接已建立");
            }

            // 测试是否能访问BlueZ根对象
            try {
                org.freedesktop.dbus.interfaces.Introspectable introspectable =
                        dbusConnection.getRemoteObject("org.bluez", "/",
                                org.freedesktop.dbus.interfaces.Introspectable.class);
                String xml = introspectable.Introspect();
                System.out.println("Introspect成功");
                System.out.println("包含ObjectManager: " + xml.contains("ObjectManager"));
            } catch (Exception e) {
                System.err.println("基础连接失败: " + e.getMessage());
            }


            // 1. 找到正确的适配器路径
            System.out.println("检查GATT管理器的适配器...");
            String adapterPath = findGATTManagerPath(dbusConnection);
            if (adapterPath == null) {
                System.err.println("未找到支持GATT管理器的适配器");
                System.exit(-1);
            }
            System.out.println("使用适配器: " + adapterPath);


            System.out.println("启动蓝牙GATT服务...");

            // 初始化WiFi管理器
            wifiManager = new WiFiManager();


            // 创建并注册GATT应用
            gattApp = new GATTApplication(dbusConnection, wifiManager);
            gattApp.register();

            System.out.println("蓝牙GATT服务启动成功");
            System.out.println("等待移动设备连接...");
            System.out.println("服务UUID: " + SERVICE_UUID);
            System.out.println("命令特性UUID: " + COMMAND_CHAR_UUID);
            System.out.println("响应特性UUID: " + RESPONSE_CHAR_UUID);
            System.out.println("状态UUID: " + STATUS_CHAR_UUID);

            // 保持程序运行
            Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));

        } catch (Exception e) {
            System.err.println("启动失败: " + e.getMessage());
            e.printStackTrace();
            shutdown();
        }
    }

    private void shutdown() {
        System.out.println("正在关闭蓝牙GATT服务...");
        if (dbusConnection != null) {
            dbusConnection.disconnect();
        }
        System.out.println("服务已关闭");
    }

    private static String findGATTManagerPath(DBusConnection dbusConnection) throws DBusException {
        try {
            ObjectManagerInterface objectManager = dbusConnection.getRemoteObject(
                    "org.bluez", "/", ObjectManagerInterface.class);

            Map<DBusPath, Map<String, Map<String, Variant<?>>>> objects = objectManager.GetManagedObjects();
//            System.out.println("获取到所有objectManager：" + JSONUtil.toJsonStr(objects));

            for (DBusPath path : objects.keySet()) {
                if (path.getPath().matches("/org/bluez/hci[0-9]+")) {
                    Map<String, Map<String, Variant<?>>> interfaces = objects.get(path);

                    // 检查是否支持GATT管理器
                    if (interfaces.containsKey("org.bluez.GattManager1")) {
                        System.out.println("找到支持GATT的适配器: " + path);
                        return path.getPath();
                    }
                }
            }

            // 如果没有找到GATT管理器，列出所有适配器
            System.out.println("未找到GATT管理器，可用适配器:");
            for (DBusPath path : objects.keySet()) {
                if (path.getPath().matches("/org/bluez/hci[0-9]+")) {
                    System.out.println("  " + path);
                    Map<String, Map<String, Variant<?>>> interfaces = objects.get(path);
                    for (String iface : interfaces.keySet()) {
                        System.out.println("    → " + iface);
                    }
                }
            }

        } catch (Exception e) {
            System.err.println("查找适配器失败: " + e.getMessage());
        }

//        return "/org/bluez/hci0"; //没返回直接返回设定好的, 然后默认的没用必须的调通这类接口才行
        return null;
    }

    public static void main(String[] args) {
        BluetoothGATTApp app = new BluetoothGATTApp();
        app.start();

        //启动一个线程去进行状态监听


        // 保持主线程运行
        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }


}
